"""
Django HttpRequest / Request 封装
"""

from django.http import HttpRequest
from rest_framework.request import Request
from user_agents import parse
from user_agents.parsers import UserAgent

from my_typing import *


class DjangoRequest:
    """ 请求 """

    class Default:
        """ 默认值 """

        BROWSER: str = "UNKNOWN"
        DEVICE: str = "UNKNOWN"
        HOST: str = "127.0.0.1"
        IP: str = "127.0.0.1"
        OS: str = "UNKNOWN"

    def __init__(self, request: HttpRequest | Request) -> None:
        self._request: HttpRequest | Request = request
        self._is_rest_request: bool = isinstance(request, Request)
        self._meta: DictOrNone = None
        self._get_meta()

    def _get_meta(self) -> None:
        """ 获取请求元数据 """

        if self._is_rest_request:
            self._meta = self._request._request.META  # noqa

        else:
            self._meta = self._request.META

    @property
    def ip(self) -> str:
        """ IP 地址 """

        if x_forwarded_for := self._meta.get("HTTP_X_FORWARDED_FOR"):
            return x_forwarded_for.split(",")[-1].strip()

        return self._meta.get("REMOTE_ADDR") or self.Default.IP

    @property
    def method(self) -> str:
        """ 请求方式（GET / POST / DELETE / PUT） """

        return self._request.method.lower()

    @property
    def path(self) -> str:
        """ 请求路径 """

        return self._request.path

    @property
    def host(self) -> str:
        """ 主机地址 """

        if self._user_agent:
            return self._user_agent.get_os()

        return self._meta.get("HTTP_HOST") or self.Default.HOST

    @property
    def query_params(self) -> dict:
        """ 获取 Query 数据 """

        data = (
            self._request.query_params
            if self._is_rest_request
            else self._request.GET
        )

        return {
            key: value
            for key, value in data.items()
        }

    @property
    def data(self) -> dict:
        """ 获取 Data 数据 """

        data = (
            self._request.data
            if self._is_rest_request
            else self._request.POST
        )

        return {
            key: value
            for key, value in data.items()
        }

    @property
    def _user_agent(self) -> UserAgent | None:
        """ 用户代理（解析自浏览器的 User-Agent） """

        if user_agent := self._meta.get("HTTP_USER_AGENT"):
            return parse(user_agent)

    @property
    def browser(self) -> str:
        """ 浏览器 """

        if self._user_agent:
            return self._user_agent.get_browser()

        return self.Default.BROWSER

    @property
    def device(self) -> str:
        """ 操作系统 """

        if self._user_agent:
            return self._user_agent.get_device()

        return self.Default.DEVICE

    @property
    def os(self) -> str:
        """ 操作系统 """

        if self._user_agent:
            return self._user_agent.get_os()

        return self.Default.OS
